﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SMS_Server;
using SMS_Server_Manager;

namespace SMS_Server_Manager.Forms
{
    public partial class InsertInto : Form
    {
        public InsertInto()
        {
            InitializeComponent();
            Connector.SelectedIndex = 0;
        }

        private Action_Insert aInsert;

        public Action_Insert Insert
        {
            get { return aInsert; }
            set
            {
                aInsert = value;
                FunctionName.Text = aInsert.ActionName;
                ParamFormat.Text = aInsert.ActionFormat;
                connectionString.Text = aInsert.ConnectionString;
                if (aInsert.Connector == Action_Insert.Connectors.OleDb) Connector.SelectedIndex = 0;
                else
                    if (aInsert.Connector == Action_Insert.Connectors.Odbc) Connector.SelectedIndex = 1;
                    else
                        Connector.SelectedIndex = 2;
                Table.Text = aInsert.TableName;
                InsertIntoColumns.Text = aInsert.Columns;
                hasResponse.Checked = aInsert.HasResponse;
                ResponseColumns.Text = aInsert.ResponseColumns;
                ResponseFormat.Text = aInsert.ResponseFormat;
            }
        }

        private Form Sender;

        public System.Windows.Forms.DialogResult ViewDialog(Form sender)
        {
            Sender = sender;
            return this.ShowDialog(sender);
        }

        private void CancleButton_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        private void ContinueButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(connectionString.Text))
            {
                MessageBox.Show("A valid connection string is required", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (!validators.IsValidString(Table.Text))
            {
                MessageBox.Show("A valid connection string is required", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            //format search columns
            string[] ParamNames;
            if (aInsert.ActionFormat.Substring(0, aInsert.ActionName.Length).ToLower() == aInsert.ActionName.ToLower())
            {
                aInsert.ActionFormat = aInsert.ActionFormat.Substring(aInsert.ActionName.Length);
            }
            aInsert.ActionFormat = aInsert.ActionFormat.Replace("[", "").Replace("]", "");
            ParamNames = aInsert.ActionFormat.Split(' ');

            if (string.IsNullOrEmpty(InsertIntoColumns.Text))
            {
                MessageBox.Show("Insert into columns are required", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string[] cols = InsertIntoColumns.Text.Replace(" ", "").Replace("[", "").Replace("]", "").Split(',');
            string refurbished = "";
            for (int i = 0; i < cols.Length; i++)
            {
                if (refurbished != "") refurbished += ",";
                refurbished += cols[i].Split('=')[0] + "=";
                if (cols[i].Split('=')[1] == "PhoneNumber") { refurbished += "[PhoneNumber]"; continue; }
                else if (cols[i].Split('=')[1] == "Date") { refurbished += "[Date]"; continue; }

                bool hasFound = false;
                for (int x = 0; x < ParamNames.Length; x++)
                {
                    if (cols[i].Split('=')[1] == ParamNames[x])
                    {
                        refurbished += "[" + ParamNames[x] + "]";
                        hasFound = true;
                        break;
                    }
                }
                if (!hasFound)
                {
                    MessageBox.Show(cols[i].Split('=')[1] + " has not been defined in the function parameter", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            InsertIntoColumns.Text = refurbished;
            //if has response, validate response parameters
            if (hasResponse.Checked)
            {
                if (string.IsNullOrEmpty(ResponseColumns.Text))
                {
                    MessageBox.Show("Response columns are required", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                string[] resp_cols = ResponseColumns.Text.Replace(" ", "").Replace("[", "").Replace("]", "").Split(',');
                string resp_refurbished = "";
                for (int i = 0; i < resp_cols.Length; i++)
                {
                    if (resp_refurbished != "") resp_refurbished += ",";
                    resp_refurbished += resp_cols[i];
                }
                ResponseColumns.Text = resp_refurbished;

                if (string.IsNullOrEmpty(ResponseFormat.Text))
                {
                    MessageBox.Show("Response format is required", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                List<string> fields = new List<string>();
                string temp = ResponseFormat.Text;
                while (temp.IndexOf("[") >= 0)
                {
                    temp = temp.Substring(temp.IndexOf("[") + 1);
                    if (temp.IndexOf("]") < 0)
                    {
                        MessageBox.Show("Parameter name must be closed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    string field = temp.Substring(0, temp.IndexOf("]"));
                    fields.Add(field);
                    temp = temp.Substring(temp.IndexOf("]") + 1);
                }
                foreach (string s in fields)
                {
                    if (s == "PhoneNumber") continue;
                    if (s == "Date") continue;
                    bool hasfound = false;
                    foreach (string str in resp_cols)
                    {
                        if (s == str)
                        {
                            hasfound = true;
                            break;
                        }
                    }
                    if (!hasfound)
                    {
                        MessageBox.Show(s + " has not been defined in response columns", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                if (fields.Count == 0)
                {
                    System.Windows.Forms.DialogResult dr = MessageBox.Show("I have not found any response column name in your message. Do you intend to send an static message?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                    if (dr == System.Windows.Forms.DialogResult.No) return;
                }
            }
            else
            {
                ResponseColumns.Text = "";
                ResponseFormat.Text = "";
            }
            aInsert.ConnectionString = connectionString.Text;
            if (Connector.SelectedIndex == 0) aInsert.Connector = Action_Insert.Connectors.OleDb; else if (Connector.SelectedIndex == 1) aInsert.Connector = Action_Insert.Connectors.Odbc; else aInsert.Connector = Action_Insert.Connectors.SQL;
            aInsert.TableName = Table.Text;
            aInsert.Columns = InsertIntoColumns.Text;
            aInsert.HasResponse = hasResponse.Checked;
            aInsert.ResponseColumns = ResponseColumns.Text;
            aInsert.ResponseFormat = ResponseFormat.Text;

            DataAccess DA = new DataAccess(Global.GetConfigurationDatabaseName(), Global.DatabasePassword);
            if (aInsert.actionID == 0)
            {
                DA.CommandString = "INSERT INTO Action_Insert (FunctionName, Format, Connector, ConnectionString, TableName, Columns, HasResponse, ResponseColumns, ResponseFormat) VALUES (@FunctionName, @Format, @Connector, @ConnectionString, @TableName, @Columns, @HasResponse, @ResponseColumns, @ResponseFormat);";
                DA.AddParameter("@FunctionName", aInsert.ActionName);
                DA.AddParameter("@Format", aInsert.ActionFormat);
                DA.AddParameter("@Connector", aInsert.Connector.ToString());
                DA.AddParameter("@ConnectionString", aInsert.ConnectionString);
                DA.AddParameter("@TableName", aInsert.TableName);
                DA.AddParameter("@Columns", aInsert.Columns);
                DA.AddParameter("@HasResponse", aInsert.HasResponse);
                DA.AddParameter("@ResponseColumns", aInsert.ResponseColumns);
                DA.AddParameter("@ResponseFormat", aInsert.ResponseFormat);
                DA.ExecuteNonQuery();
                DA.CommandString = "SELECT ActionID FROM Action_Insert WHERE FunctionName=@FunctionName AND Format=@Format AND  Connector=@Connector AND ConnectionString=@ConnectionString AND TableName=@TableName AND Columns=@Columns AND HasResponse=@HasResponse AND ResponseColumns=@ResponseColumns AND ResponseFormat=@ResponseFormat;";
                DA.ExecuteReader();
                while (DA.Reader.Read())
                {
                    int ActionID = (int)DA.Reader.GetInt64(0);
                    bool ActionExist = false;
                    foreach (Incoming_Action ia in ((Function)((Mainform)Sender).FunctionList.SelectedItem).Actions)
                    {
                        if (ia.ActionID() == (long)ActionID && ia.ActionType() == ActionTypes.StaticResponse)
                        {
                            ActionExist = true;
                        }
                    }
                    if (!ActionExist)
                    {
                        aInsert.actionID = ActionID;
                        ((Function)((Mainform)Sender).FunctionList.SelectedItem).Actions.Add(aInsert);
                        break;
                    }
                }
                DA.Reader.Close();
                DA.Close();
                ((Mainform)Sender).ActionList.Items.Add(aInsert);
            }
            else
            {
                DA.CommandString = "UPDATE Action_Insert SET Connector=@Connector, ConnectionString=@ConnectionString, TableName=@TableName, Columns=@Columns, HasResponse=@HasResponse, ResponseColumns=@ResponseColumns, ResponseFormat=@ResponseFormat WHERE ActionID=@ActionID;";
                DA.AddParameter("@Connector", aInsert.Connector.ToString());
                DA.AddParameter("@ConnectionString", aInsert.ConnectionString);
                DA.AddParameter("@TableName", aInsert.TableName);
                DA.AddParameter("@Columns", aInsert.Columns);
                DA.AddParameter("@HasResponse", aInsert.HasResponse);
                DA.AddParameter("@ResponseColumns", aInsert.ResponseColumns);
                DA.AddParameter("@ResponseFormat", aInsert.ResponseFormat);
                DA.AddParameter("@ActionID", aInsert.actionID);
                DA.ExecuteNonQuery();
                DA.Close();
            }
            Global.unsaved_changes = true;
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }
    }
}
